<template>
  <div class="tryon-container">
    <!-- 顶部导航栏 -->
    <div class="navbar glass-effect">
      <div class="navbar-content">
        <div class="brand">
          <svg viewBox="0 0 40 40" class="brand-logo">
            <defs>
              <linearGradient id="logoGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#ec4899;stop-opacity:1" />
                <stop offset="50%" style="stop-color:#d946ef;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
              </linearGradient>
            </defs>
            <path d="M20 4 L36 12 L36 28 L20 36 L4 28 L4 12 Z" 
                  fill="url(#logoGradient)" stroke="white" stroke-width="1"/>
            <circle cx="20" cy="16" r="3" fill="white"/>
            <rect x="17" y="20" width="6" height="12" rx="1" fill="white"/>
          </svg>
          <h1 class="brand-name gradient-text">智能试衣间</h1>
        </div>
        
        <!-- 桌面端菜单 -->
        <div class="nav-actions desktop-menu">
          <el-button 
            @click="$router.push('/wardrobe')" 
            :icon="Suitcase"
            class="nav-btn"
          >
            我的衣橱
          </el-button>
          <el-button 
            @click="$router.push('/history')" 
            :icon="Clock"
            class="nav-btn"
          >
            历史记录
          </el-button>
          <el-button 
            type="danger" 
            @click="handleLogout"
            :icon="SwitchButton"
            class="nav-btn"
          >
            退出登录
          </el-button>
        </div>
        
        <!-- 移动端汉堡菜单 -->
        <el-button 
          class="mobile-menu-btn" 
          :icon="Menu"
          circle
          @click="mobileMenuVisible = true"
        />
      </div>
    </div>
    
    <!-- 移动端抽屉菜单 -->
    <el-drawer
      v-model="mobileMenuVisible"
      direction="rtl"
      size="280px"
      :show-close="false"
      class="mobile-drawer"
    >
      <template #header>
        <div class="drawer-header">
          <svg viewBox="0 0 40 40" class="drawer-logo">
            <defs>
              <linearGradient id="drawerLogoGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#ec4899;stop-opacity:1" />
                <stop offset="50%" style="stop-color:#d946ef;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#8b5cf6;stop-opacity:1" />
              </linearGradient>
            </defs>
            <path d="M20 4 L36 12 L36 28 L20 36 L4 28 L4 12 Z" 
                  fill="url(#drawerLogoGradient)" stroke="white" stroke-width="1"/>
            <circle cx="20" cy="16" r="3" fill="white"/>
            <rect x="17" y="20" width="6" height="12" rx="1" fill="white"/>
          </svg>
          <h2 class="gradient-text">菜单</h2>
        </div>
      </template>
      
      <div class="drawer-menu">
        <div class="menu-section">
          <div class="menu-section-title">功能</div>
          <div 
            class="menu-item"
            @click="navigateTo('/tryon')"
          >
            <el-icon class="menu-icon"><MagicStick /></el-icon>
            <span class="menu-text">智能试衣</span>
          </div>
          <div 
            class="menu-item"
            @click="navigateTo('/wardrobe')"
          >
            <el-icon class="menu-icon"><Suitcase /></el-icon>
            <span class="menu-text">我的衣橱</span>
          </div>
          <div 
            class="menu-item"
            @click="navigateTo('/history')"
          >
            <el-icon class="menu-icon"><Clock /></el-icon>
            <span class="menu-text">历史记录</span>
          </div>
        </div>
        
        <div class="menu-divider"></div>
        
        <div class="menu-section">
          <div class="menu-section-title">账户</div>
          <div 
            class="menu-item menu-item-danger"
            @click="handleLogout"
          >
            <el-icon class="menu-icon"><SwitchButton /></el-icon>
            <span class="menu-text">退出登录</span>
          </div>
        </div>
        
        <div class="menu-footer">
          <div class="user-info">
            <el-icon class="user-avatar"><Avatar /></el-icon>
            <div class="user-details">
              <div class="user-name">{{ authStore.user?.username || '用户' }}</div>
              <div class="user-email">{{ authStore.user?.email || '' }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="content-wrapper">
        <!-- 左侧：上传区域 -->
        <div class="upload-section">
          <div class="section-card animate-fade-in-up">
            <div class="card-header">
              <h2 class="card-title">
                <el-icon class="title-icon"><Upload /></el-icon>
                上传照片
              </h2>
              <p class="card-subtitle">上传您的照片和心仪的服装</p>
            </div>
            
            <!-- 上传用户照片 -->
            <div class="upload-group">
              <div class="upload-label">
                <span class="label-icon">👤</span>
                <span class="label-text">您的照片</span>
                <el-tag size="small" type="info">全身照</el-tag>
              </div>
              
              <!-- 选择方式：上传或从库中选择 -->
              <div class="source-selector">
                <el-button 
                  :type="personSource === 'upload' ? 'primary' : ''"
                  size="small"
                  @click="personSource = 'upload'"
                >
                  上传照片
                </el-button>
                <el-button 
                  :type="personSource === 'library' ? 'primary' : ''"
                  size="small"
                  @click="selectFromPersonLibrary"
                >
                  从形象库选择
                </el-button>
              </div>
              
              <el-upload
                v-if="personSource === 'upload'"
                :key="'person-' + Math.random()"
                class="custom-upload"
                drag
                :http-request="uploadPersonImage"
                :before-upload="beforeUpload"
                :show-file-list="false"
              >
                <div v-if="!personImageUrl" class="upload-placeholder">
                  <el-icon class="upload-icon"><UploadFilled /></el-icon>
                  <div class="upload-text">点击或拖拽上传</div>
                  <div class="upload-hint">支持 JPG、PNG 格式，最大 10MB</div>
                </div>
                <div v-else class="upload-preview">
                  <img :src="personImageUrl" alt="用户照片" />
                  <div class="preview-overlay">
                    <el-icon class="overlay-icon"><RefreshRight /></el-icon>
                    <span>重新上传</span>
                  </div>
                </div>
              </el-upload>
              
              <!-- 从形象库选择 -->
              <div v-else class="library-selector">
                <div v-if="personImageUrl" class="selected-preview">
                  <img :src="personImageUrl" alt="已选择" />
                  <el-button 
                    size="small" 
                    @click="selectFromPersonLibrary"
                  >
                    重新选择
                  </el-button>
                </div>
                <el-button 
                  v-else
                  type="primary"
                  @click="selectFromPersonLibrary"
                >
                  从形象库选择
                </el-button>
              </div>
              
              <!-- 保存到形象库选项 -->
              <div v-if="personSource === 'upload' && personImageUrl" class="save-option">
                <el-checkbox v-model="savePersonToLibrary">保存到形象库</el-checkbox>
                <el-input 
                  v-if="savePersonToLibrary"
                  v-model="personName"
                  placeholder="形象名称（可选）"
                  size="small"
                  style="margin-top: 0.5rem;"
                />
              </div>
            </div>
            
            <!-- 上传服装照片 - 使用多件上传组件 -->
            <MultiGarmentUpload 
              v-model="garments"
              :user-id="userId"
              :max-garments="5"
            />
            
            <!-- 开始试衣按钮 -->
            <el-button 
              type="primary" 
              size="large" 
              class="tryon-button"
              :loading="processing"
              :disabled="!personImageUrl || garments.filter(g => g.imageUrl).length === 0"
              @click="handleTryOn"
            >
              <el-icon v-if="!processing"><MagicStick /></el-icon>
              <span v-if="!processing">
                开始 AI 试衣
                <span v-if="garments.filter(g => g.imageUrl).length > 0">
                  ({{ garments.filter(g => g.imageUrl).length }}件)
                </span>
              </span>
              <span v-else>AI 处理中...</span>
            </el-button>
          </div>
        </div>
        
        <!-- 右侧：结果显示 -->
        <div class="result-section">
          <div class="section-card animate-fade-in-up" style="animation-delay: 0.2s">
            <div class="card-header">
              <h2 class="card-title">
                <el-icon class="title-icon"><Picture /></el-icon>
                试衣效果
              </h2>
              <p class="card-subtitle">AI 生成的试穿预览</p>
            </div>
            
            <!-- 加载状态 -->
            <div v-if="processing" class="loading-state">
              <div class="loading-animation">
                <div class="magic-circle">
                  <div class="sparkle sparkle-1"></div>
                  <div class="sparkle sparkle-2"></div>
                  <div class="sparkle sparkle-3"></div>
                  <div class="sparkle sparkle-4"></div>
                  <el-icon class="magic-icon rotating"><MagicStick /></el-icon>
                </div>
              </div>
              <h3 class="loading-title">AI 正在施展魔法 ✨</h3>
              <p class="loading-description">请稍候，正在为您生成完美的试衣效果...</p>
              <el-progress 
                :percentage="loadingProgress" 
                :stroke-width="8"
                :show-text="false"
                class="loading-progress"
              />
              <p class="loading-tip">{{ loadingTip }}</p>
            </div>
            
            <!-- 空状态 -->
            <div v-else-if="!resultImageUrl" class="empty-result">
              <div class="empty-illustration">
                <div class="illustration-circle">
                  <el-icon class="illustration-icon"><MagicStick /></el-icon>
                </div>
              </div>
              <h3 class="empty-title">准备开始试衣</h3>
              <p class="empty-description">
                上传您的照片和心仪的服装<br/>
                让 AI 为您呈现完美的试穿效果
              </p>
              <div class="empty-features">
                <div class="feature-tag">
                  <el-icon><Lightning /></el-icon>
                  <span>秒级生成</span>
                </div>
                <div class="feature-tag">
                  <el-icon><View /></el-icon>
                  <span>真实预览</span>
                </div>
                <div class="feature-tag">
                  <el-icon><Star /></el-icon>
                  <span>专业效果</span>
                </div>
              </div>
            </div>
            
            <!-- 结果显示 -->
            <div v-else class="result-display">
              <div class="result-image-wrapper">
                <img :src="resultImageUrl" class="result-image" alt="试衣效果" />
                <div class="image-badge">
                  <el-icon><Check /></el-icon>
                  <span>AI 已生成</span>
                </div>
              </div>
              
              <div class="result-actions">
                <el-button 
                  type="success" 
                  size="large"
                  :icon="Download"
                  @click="handleSave"
                  class="action-btn"
                >
                  保存效果
                </el-button>
                <el-button 
                  type="primary" 
                  size="large"
                  :icon="Share"
                  @click="handleShare"
                  class="action-btn"
                >
                  分享效果
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 选择形象对话框 -->
    <el-dialog 
      v-model="personLibraryDialogVisible" 
      title="从形象库选择"
      width="900px"
      :fullscreen="isMobile"
      class="library-dialog"
    >
      <div class="library-grid">
        <div 
          v-for="person in personLibraryList" 
          :key="person.id"
          :class="['library-item', { 'selected': selectedPersonId === person.id }]"
          @click="selectedPersonId = person.id"
        >
          <img :src="person.imageUrl" :alt="person.personName || '形象'" />
          <div class="library-item-info">
            <span>{{ person.personName || '未命名形象' }}</span>
          </div>
          <div v-if="selectedPersonId === person.id" class="selected-badge">
            <el-icon><Check /></el-icon>
          </div>
        </div>
      </div>
      <div v-if="personLibraryList.length === 0" class="empty-library">
        <p>形象库还是空的，先去添加一些照片吧</p>
        <el-button type="primary" @click="$router.push('/wardrobe')">前往衣橱</el-button>
      </div>
      <template #footer>
        <el-button @click="personLibraryDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmSelectPerson"
          :disabled="!selectedPersonId"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 底部导航 -->
    <BottomNav />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  UploadFilled, 
  Picture, 
  MagicStick, 
  Clock, 
  SwitchButton,
  Upload,
  RefreshRight,
  Download,
  Share,
  Lightning,
  View,
  Star,
  Check,
  Suitcase,
  Menu,
  Avatar
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import api from '@/composables/useApi'
import BottomNav from '@/components/BottomNav.vue'
import MultiGarmentUpload from '@/components/MultiGarmentUpload.vue'

// @generatedBy AI-CodeGen
// @lastModified 2025-10-29 - 添加多件服装支持

const router = useRouter()
const authStore = useAuthStore()

// 检测是否为移动端
const isMobile = ref(window.innerWidth <= 768)

// 监听窗口大小变化
window.addEventListener('resize', () => {
  isMobile.value = window.innerWidth <= 768
})

// 移动端菜单状态
const mobileMenuVisible = ref(false)

// 导航到指定页面
const navigateTo = (path) => {
  mobileMenuVisible.value = false
  router.push(path)
}

const personImageUrl = ref('')
const resultImageUrl = ref('')
const processing = ref(false)
const loadingProgress = ref(0)
const loadingTip = ref('正在上传图片...')
const currentHistoryId = ref(null) // 保存当前试衣的历史记录ID

// 数据来源：'upload' 或 'library'
const personSource = ref('upload')

// 多件服装数据（替换单件服装）
const garments = ref([{
  id: Date.now(),
  imageUrl: '',
  type: '',
  name: '',
  remarks: '',
  uploading: false,
  garmentId: null,
  saveToLibrary: false
}])

// 形象信息
const personName = ref('')
const personId = ref(null)

// 是否保存到库
const savePersonToLibrary = ref(false)

// 库选择对话框
const personLibraryDialogVisible = ref(false)
const personLibraryList = ref([])
const selectedPersonId = ref(null)

// 用户ID（从登录状态获取）
const userId = computed(() => authStore.user?.id || 1)

const beforeUpload = (file) => {
  console.log('📤 上传文件信息:', {
    name: file.name,
    type: file.type,
    size: file.size,
    lastModified: file.lastModified
  })
  
  // 检查文件类型 - 兼容 iPhone HEIC 格式和云端照片
  const validTypes = [
    'image/jpeg',
    'image/jpg', 
    'image/png',
    'image/heic',  // iPhone HEIC 格式
    'image/heif',
    ''  // 某些情况下 type 可能为空（如 iCloud 照片）
  ]
  
  // 通过 MIME 类型或文件扩展名验证
  const isValidType = validTypes.includes(file.type) || 
                     file.name.match(/\.(jpg|jpeg|png|heic|heif)$/i)
  
  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/HEIC 格式的图片！')
    console.error('❌ 不支持的文件类型:', file.type, file.name)
    return false
  }
  
  // 检查文件大小 - 对于云端图片，size 可能为 0，所以只在 size > 0 时检查
  if (file.size > 0) {
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      ElMessage.error('图片大小不能超过 10MB！')
      return false
    }
  } else {
    // 云端图片，显示提示
    console.log('⚠️ 检测到云端图片（size=0），正在下载...')
    ElMessage.info('正在从 iCloud 下载照片，请稍候...')
  }
  
  // 检测实况照片
  if (file.name.toLowerCase().includes('live')) {
    ElMessage.info('检测到实况照片，将使用静态图片部分')
  }
  
  return true
}

// 上传用户照片到后端
const uploadPersonImage = async (options) => {
  const { file, onProgress, onSuccess, onError } = options
  
  try {
    ElMessage.info('正在上传用户照片...')
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', userId.value)
    formData.append('saveToLibrary', savePersonToLibrary.value)
    if (savePersonToLibrary.value && personName.value) {
      formData.append('personName', personName.value)
    }
    
    // 上传到后端
    const response = await api.post('/tryon/upload/person', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        if (onProgress) {
          onProgress({ percent })
        }
      }
    })
    
    // 设置图片URL
    personImageUrl.value = response.data.url
    if (response.data.personId) {
      personId.value = response.data.personId
    }
    
    ElMessage.success({
      message: savePersonToLibrary.value ? '照片已上传并保存到形象库 ✨' : '用户照片上传成功 ✨',
      duration: 2000
    })
    
    if (onSuccess) {
      onSuccess(response.data)
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.response?.data?.message || '上传失败，请重试')
    if (onError) {
      onError(error)
    }
  }
}

// 上传服装照片到后端
const uploadGarmentImage = async (options) => {
  const { file, onProgress, onSuccess, onError } = options
  
  try {
    // 验证必填字段
    if (!garmentType.value) {
      ElMessage.warning('请先选择服装类型')
      if (onError) {
        onError(new Error('请先选择服装类型'))
      }
      return
    }
    
    ElMessage.info('正在上传服装照片...')
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    formData.append('userId', userId.value)
    formData.append('garmentType', garmentType.value) // 总是发送类型
    formData.append('saveToLibrary', saveGarmentToLibrary.value)
    
    // 发送可选字段
    if (garmentName.value) {
      formData.append('garmentName', garmentName.value)
    }
    if (garmentRemarks.value) {
      formData.append('remarks', garmentRemarks.value)
    }
    
    // 上传到后端
    const response = await api.post('/tryon/upload/garment', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        if (onProgress) {
          onProgress({ percent })
        }
      }
    })
    
    // 设置图片URL
    garmentImageUrl.value = response.data.url
    if (response.data.garmentId) {
      garmentId.value = response.data.garmentId
    }
    
    ElMessage.success({
      message: saveGarmentToLibrary.value ? '服装已上传并保存到衣橱 ✨' : '服装照片上传成功 ✨',
      duration: 2000
    })
    
    if (onSuccess) {
      onSuccess(response.data)
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.response?.data?.message || '上传失败，请重试')
    if (onError) {
      onError(error)
    }
  }
}

const handleTryOn = async () => {
  // 过滤出有效的服装（已上传且选择了类型）
  const validGarments = garments.value.filter(g => g.imageUrl && g.type)
  
  if (!personImageUrl.value) {
    ElMessage.warning('请先上传您的照片')
    return
  }
  
  if (validGarments.length === 0) {
    ElMessage.warning('请至少上传一件服装图片')
    return
  }
  
  processing.value = true
  loadingProgress.value = 0
  currentHistoryId.value = null
  
  // 模拟加载进度
  const progressInterval = setInterval(() => {
    if (loadingProgress.value < 90) {
      loadingProgress.value += Math.random() * 10
      
      // 更新提示文字
      if (loadingProgress.value < 30) {
        loadingTip.value = `正在分析 ${validGarments.length} 件服装特征...`
      } else if (loadingProgress.value < 60) {
        loadingTip.value = 'AI 正在理解搭配风格...'
      } else {
        loadingTip.value = '正在生成完美试衣效果...'
      }
    }
  }, 500)
  
  try {
    const response = await api.post('/tryon/process', {
      personImageUrl: personImageUrl.value,
      garments: validGarments.map(g => ({
        imageUrl: g.imageUrl,
        type: g.type,
        name: g.name || '',
        garmentId: g.garmentId
      })),
      userId: userId.value
    })
    
    clearInterval(progressInterval)
    loadingProgress.value = 100
    loadingTip.value = '完成！'
    
    resultImageUrl.value = response.data.resultUrl
    currentHistoryId.value = response.data.historyId // 保存历史记录ID
    
    ElMessage.success({
      message: `试穿完成！${validGarments.length}件服装搭配效果超赞 🎉`,
      duration: 3000
    })
  } catch (error) {
    clearInterval(progressInterval)
    ElMessage.error(error.response?.data?.message || 'AI 处理失败，请稍后重试')
  } finally {
    processing.value = false
  }
}

const handleSave = async () => {
  if (!resultImageUrl.value) {
    ElMessage.warning('还没有试衣结果可以保存')
    return
  }
  
  try {
    // 如果已经有历史记录ID，说明已经自动保存了
    if (currentHistoryId.value) {
      ElMessage.success('试衣效果已自动保存到历史记录 ✨')
      router.push('/history')
      return
    }
    
    // 手动保存
    const response = await api.post('/tryon/history/save', {
      userId: userId.value,
      personImageUrl: personImageUrl.value,
      garmentId: garmentId.value,
      garmentImageUrl: garmentImageUrl.value,
      resultImageUrl: resultImageUrl.value,
      garmentType: garmentType.value
    })
    
    currentHistoryId.value = response.data.id
    ElMessage.success('保存成功！已添加到历史记录 ✨')
    
    // 询问是否查看历史记录
    setTimeout(() => {
      ElMessageBox.confirm('是否前往查看历史记录？', '提示', {
        confirmButtonText: '查看',
        cancelButtonText: '继续试衣',
        type: 'success'
      }).then(() => {
        router.push('/history')
      }).catch(() => {
        // 用户选择继续试衣
      })
    }, 500)
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败：' + (error.response?.data?.message || error.message))
  }
}

const handleShare = () => {
  ElMessage.info('分享功能开发中，敬请期待 🚀')
  // TODO: 实现分享功能
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 从衣橱选择
const selectFromGarmentLibrary = async () => {
  try {
    const response = await api.get('/tryon/garments', {
      params: { userId: userId.value }
    })
    garmentLibraryList.value = response.data.garments || []
    selectedGarmentId.value = null
    garmentLibraryDialogVisible.value = true
  } catch (error) {
    console.error('加载衣橱失败:', error)
    ElMessage.error('加载衣橱失败')
  }
}

// 确认选择衣服
const confirmSelectGarment = () => {
  const garment = garmentLibraryList.value.find(g => g.id === selectedGarmentId.value)
  if (garment) {
    garmentImageUrl.value = garment.imageUrl
    garmentId.value = garment.id
    garmentType.value = garment.garmentType
    garmentName.value = garment.garmentName
    garmentLibraryDialogVisible.value = false
    ElMessage.success('已选择: ' + (garment.garmentName || '服装'))
  }
}

// 从形象库选择
const selectFromPersonLibrary = async () => {
  try {
    const response = await api.get('/tryon/persons', {
      params: { userId: userId.value }
    })
    personLibraryList.value = response.data.persons || []
    selectedPersonId.value = null
    personLibraryDialogVisible.value = true
  } catch (error) {
    console.error('加载形象库失败:', error)
    ElMessage.error('加载形象库失败')
  }
}

// 确认选择形象
const confirmSelectPerson = () => {
  const person = personLibraryList.value.find(p => p.id === selectedPersonId.value)
  if (person) {
    personImageUrl.value = person.imageUrl
    personId.value = person.id
    personLibraryDialogVisible.value = false
    ElMessage.success('已选择: ' + (person.personName || '形象'))
  }
}
</script>

<style scoped>
.tryon-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #fdf2f8 0%, #fae8ff 50%, #f3e8ff 100%);
}

/* 导航栏 */
.navbar {
  position: sticky;
  top: 0;
  z-index: 100;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(217, 70, 239, 0.1);
  box-shadow: 0 4px 20px rgba(217, 70, 239, 0.08);
}

.navbar-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.brand {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.brand-logo {
  width: 40px;
  height: 40px;
  filter: drop-shadow(0 2px 8px rgba(217, 70, 239, 0.3));
}

.brand-name {
  font-size: 1.5rem;
  font-weight: 700;
  margin: 0;
}

.nav-actions {
  display: flex;
  gap: 1rem;
}

/* 移动端汉堡菜单按钮 */
.mobile-menu-btn {
  display: none;
  background: linear-gradient(135deg, #ec4899 0%, #d946ef 50%, #8b5cf6 100%);
  border: none;
  color: white;
  width: 40px;
  height: 40px;
  box-shadow: 0 4px 12px rgba(217, 70, 239, 0.3);
  transition: all 0.3s ease;
}

.mobile-menu-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(217, 70, 239, 0.4);
}

.nav-btn {
  border-radius: 10px;
}

/* 主内容区域 */
.main-content {
  padding: 2rem;
}

.content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
}

/* 卡片样式 */
.section-card {
  background: white;
  border-radius: 24px;
  padding: 2rem;
  box-shadow: 0 10px 40px rgba(217, 70, 239, 0.1);
  border: 1px solid rgba(217, 70, 239, 0.1);
  transition: all 0.3s ease;
}

.section-card:hover {
  box-shadow: 0 20px 60px rgba(217, 70, 239, 0.15);
  transform: translateY(-2px);
}

.card-header {
  margin-bottom: 2rem;
  text-align: center;
}

.card-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  font-size: 1.75rem;
  font-weight: 700;
  background: linear-gradient(135deg, #ec4899, #d946ef, #8b5cf6);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0 0 0.5rem 0;
}

.title-icon {
  font-size: 1.75rem;
  color: #d946ef;
}

.card-subtitle {
  color: #64748b;
  font-size: 0.95rem;
  margin: 0;
}

/* 上传组件 */
.upload-group {
  margin-bottom: 1.5rem;
}

.upload-label {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1rem;
  font-weight: 600;
  color: #1e293b;
  font-size: 1rem;
}

.label-icon {
  font-size: 1.5rem;
}

.label-text {
  flex: 1;
}

.custom-upload {
  width: 100%;
}

.custom-upload :deep(.el-upload) {
  width: 100%;
}

.custom-upload :deep(.el-upload-dragger) {
  width: 100%;
  height: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #d946ef !important;
  border-radius: 16px !important;
  background: linear-gradient(135deg, #fdf4ff 0%, #fae8ff 100%);
  transition: all 0.3s ease !important;
}

.custom-upload :deep(.el-upload-dragger:hover) {
  border-color: #c026d3 !important;
  background: linear-gradient(135deg, #fae8ff 0%, #f3e8ff 100%);
  transform: scale(1.02);
}

.upload-placeholder {
  text-align: center;
}

.upload-icon {
  font-size: 3rem;
  color: #d946ef;
  margin-bottom: 1rem;
}

.upload-text {
  font-size: 1.1rem;
  color: #475569;
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.upload-hint {
  font-size: 0.85rem;
  color: #94a3b8;
}

.upload-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.upload-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 14px;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(217, 70, 239, 0.9);
  border-radius: 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  font-weight: 600;
}

.upload-preview:hover .preview-overlay {
  opacity: 1;
}

.overlay-icon {
  font-size: 2rem;
}

/* 试衣按钮 */
.tryon-button {
  width: 100%;
  height: 56px;
  font-size: 1.1rem;
  font-weight: 700;
  border-radius: 14px;
  margin-top: 1rem;
  box-shadow: 0 8px 20px rgba(217, 70, 239, 0.3);
}

.tryon-button:hover:not(:disabled) {
  box-shadow: 0 12px 30px rgba(217, 70, 239, 0.4);
}

/* 空状态 */
.empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 500px;
  text-align: center;
  padding: 2rem;
}

.empty-illustration {
  margin-bottom: 2rem;
}

.illustration-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #fdf4ff, #fae8ff);
  border: 3px dashed #d946ef;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: float 3s ease-in-out infinite;
}

.illustration-icon {
  font-size: 3.5rem;
  color: #d946ef;
}

.empty-title {
  font-size: 1.75rem;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 1rem 0;
}

.empty-description {
  font-size: 1rem;
  line-height: 1.6;
  color: #64748b;
  margin: 0 0 2rem 0;
}

.empty-features {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
  justify-content: center;
}

.feature-tag {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: linear-gradient(135deg, #fdf4ff, #fae8ff);
  border: 1px solid #f0abfc;
  border-radius: 50px;
  color: #c026d3;
  font-weight: 600;
  font-size: 0.9rem;
}

/* 结果显示 */
.result-display {
  padding: 1rem;
}

.result-image-wrapper {
  position: relative;
  margin-bottom: 1.5rem;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 30px rgba(217, 70, 239, 0.2);
}

.result-image {
  width: 100%;
  height: auto;
  display: block;
}

.image-badge {
  position: absolute;
  top: 1rem;
  right: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: rgba(16, 185, 129, 0.95);
  backdrop-filter: blur(10px);
  color: white;
  border-radius: 50px;
  font-weight: 600;
  font-size: 0.9rem;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.result-actions {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.action-btn {
  height: 48px;
  font-weight: 600;
  border-radius: 12px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-wrapper {
    grid-template-columns: 1fr;
  }
  
  .navbar-content {
    padding: 1rem;
  }
  
  .brand-name {
    font-size: 1.25rem;
  }
  
  .nav-actions {
    gap: 0.5rem;
  }
}

/* 手机端优化 - 移动优先 */
@media (max-width: 640px) {
  /* 导航栏优化 */
  .navbar-content {
    padding: 0.75rem 1rem;
    flex-wrap: wrap;
  }
  
  .brand {
    gap: 0.5rem;
  }
  
  .brand-logo {
    width: 32px;
    height: 32px;
  }
  
  .brand-name {
    font-size: 1.125rem;
  }
  
  .nav-actions {
    width: 100%;
    margin-top: 0.75rem;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.5rem;
  }
  
  .nav-btn {
    width: 100%;
    justify-content: center;
  }
  
  .nav-btn :deep(.el-button__text) {
    font-size: 0.875rem;
  }
  
  /* 主内容区域 */
  .main-content {
    padding: 0.75rem;
  }
  
  .content-wrapper {
    gap: 1rem;
  }
  
  /* 卡片优化 */
  .section-card {
    padding: 1.25rem;
    border-radius: 20px;
  }
  
  .card-header {
    margin-bottom: 1.5rem;
  }
  
  .card-title {
    font-size: 1.25rem;
    gap: 0.5rem;
  }
  
  .title-icon {
    font-size: 1.25rem;
  }
  
  .card-subtitle {
    font-size: 0.875rem;
  }
  
  /* 上传区域优化 */
  .upload-group {
    margin-bottom: 1.25rem;
  }
  
  .upload-label {
    font-size: 0.9rem;
    gap: 0.5rem;
  }
  
  .label-icon {
    font-size: 1.25rem;
  }
  
  .custom-upload :deep(.el-upload-dragger) {
    height: 220px;
  }
  
  .upload-icon {
    font-size: 2.5rem;
    margin-bottom: 0.75rem;
  }
  
  .upload-text {
    font-size: 1rem;
  }
  
  .upload-hint {
    font-size: 0.8rem;
  }
  
  .overlay-icon {
    font-size: 1.75rem;
  }
  
  /* 试衣按钮优化 */
  .tryon-button {
    height: 52px;
    font-size: 1.05rem;
    border-radius: 12px;
    margin-top: 0.75rem;
  }
  
  /* 空状态优化 */
  .empty-result {
    min-height: 400px;
    padding: 1.5rem;
  }
  
  .illustration-circle {
    width: 100px;
    height: 100px;
  }
  
  .illustration-icon {
    font-size: 3rem;
  }
  
  .empty-title {
    font-size: 1.5rem;
  }
  
  .empty-description {
    font-size: 0.95rem;
  }
  
  .empty-features {
    gap: 0.75rem;
  }
  
  .feature-tag {
    padding: 0.4rem 0.85rem;
    font-size: 0.85rem;
  }
  
  /* 结果显示优化 */
  .result-display {
    padding: 0.5rem;
  }
  
  .result-image-wrapper {
    margin-bottom: 1rem;
    border-radius: 12px;
  }
  
  .image-badge {
    top: 0.75rem;
    right: 0.75rem;
    padding: 0.4rem 0.85rem;
    font-size: 0.85rem;
  }
  
  .result-actions {
    grid-template-columns: 1fr;
    gap: 0.75rem;
  }
  
  .action-btn {
    height: 50px;
    font-size: 1rem;
    border-radius: 12px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 375px) {
  .navbar-content {
    padding: 0.6rem 0.75rem;
  }
  
  .brand-name {
    font-size: 1rem;
  }
  
  .section-card {
    padding: 1rem;
  }
  
  .card-title {
    font-size: 1.125rem;
  }
  
  .custom-upload :deep(.el-upload-dragger) {
    height: 200px;
  }
  
  .tryon-button {
    height: 50px;
    font-size: 1rem;
  }
  
  .action-btn {
    height: 48px;
    font-size: 0.95rem;
  }
}

/* 横屏优化 */
@media (max-width: 896px) and (orientation: landscape) {
  .navbar-content {
    padding: 0.5rem 1rem;
  }
  
  .nav-actions {
    margin-top: 0;
    width: auto;
  }
  
  .empty-result {
    min-height: 300px;
  }
  
  .illustration-circle {
    width: 80px;
    height: 80px;
  }
  
  .illustration-icon {
    font-size: 2.5rem;
  }
}

/* 新增样式 - 来源选择器 */
.source-selector {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

/* 库选择器 */
.library-selector {
  min-height: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #fdf4ff 0%, #fae8ff 100%);
  border: 2px dashed #d946ef;
  border-radius: 16px;
  padding: 1rem;
}

.selected-preview {
  position: relative;
  text-align: center;
}

.selected-preview img {
  max-width: 100%;
  max-height: 250px;
  border-radius: 12px;
  margin-bottom: 0.75rem;
}

/* 保存选项 */
.save-option,
.garment-info {
  margin-top: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 12px;
}

.garment-form {
  margin-top: 0.5rem;
}

/* 服装类型选择器 */
.garment-type-selector {
  margin-bottom: 1rem;
  padding: 1rem;
  background: linear-gradient(135deg, #fff5f7 0%, #fff1f7 100%);
  border: 2px solid #fbbf24;
  border-radius: 12px;
}

.field-label {
  display: block;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 0.5rem;
  font-size: 0.95rem;
}

.required {
  color: #ef4444;
  margin-left: 0.25rem;
}

/* 服装详细信息 */
.garment-details {
  margin-top: 1rem;
  padding: 1rem;
  background: linear-gradient(135deg, #f0fdf4 0%, #ecfdf5 100%);
  border: 1px solid #86efac;
  border-radius: 12px;
}

.garment-details :deep(.el-input-group__prepend) {
  background: white;
  font-weight: 600;
}

/* 库网格 */
.library-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 1rem;
  max-height: 60vh;
  overflow-y: auto;
  padding: 0.5rem;
}

.library-item {
  position: relative;
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  border: 3px solid transparent;
  transition: all 0.3s ease;
}

.library-item:hover {
  border-color: #d946ef;
  transform: scale(1.05);
}

.library-item.selected {
  border-color: #d946ef;
  box-shadow: 0 4px 12px rgba(217, 70, 239, 0.3);
}

.library-item img {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.library-item-info {
  padding: 0.5rem;
  background: white;
  text-align: center;
  font-size: 0.875rem;
  font-weight: 500;
  color: #475569;
}

.selected-badge {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  width: 32px;
  height: 32px;
  background: #10b981;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.25rem;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

.empty-library {
  text-align: center;
  padding: 2rem;
  color: #64748b;
}

.empty-library p {
  margin-bottom: 1rem;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 500px;
  text-align: center;
  padding: 2rem;
}

.loading-animation {
  margin-bottom: 2rem;
}

.magic-circle {
  position: relative;
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: pulse 2s ease-in-out infinite;
}

.magic-icon {
  font-size: 4rem;
  color: #d946ef;
  z-index: 2;
}

.rotating {
  animation: rotate 3s linear infinite;
}

.sparkle {
  position: absolute;
  width: 12px;
  height: 12px;
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  border-radius: 50%;
  animation: sparkle 1.5s ease-in-out infinite;
}

.sparkle-1 {
  top: 10%;
  left: 50%;
  animation-delay: 0s;
}

.sparkle-2 {
  top: 50%;
  right: 10%;
  animation-delay: 0.375s;
}

.sparkle-3 {
  bottom: 10%;
  left: 50%;
  animation-delay: 0.75s;
}

.sparkle-4 {
  top: 50%;
  left: 10%;
  animation-delay: 1.125s;
}

.loading-title {
  font-size: 1.75rem;
  font-weight: 700;
  background: linear-gradient(135deg, #ec4899, #d946ef, #8b5cf6);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0 0 1rem 0;
}

.loading-description {
  font-size: 1rem;
  color: #64748b;
  margin: 0 0 2rem 0;
}

.loading-progress {
  width: 100%;
  max-width: 400px;
  margin-bottom: 1rem;
}

.loading-progress :deep(.el-progress-bar__outer) {
  background: rgba(217, 70, 239, 0.1);
}

.loading-progress :deep(.el-progress-bar__inner) {
  background: linear-gradient(90deg, #ec4899, #d946ef, #8b5cf6);
}

.loading-tip {
  font-size: 0.9rem;
  color: #94a3b8;
  margin: 0;
  font-weight: 500;
}

/* 动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes sparkle {
  0%, 100% {
    opacity: 0;
    transform: scale(0);
  }
  50% {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

/* 对话框移动端适配 */
@media (max-width: 768px) {
  .library-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .library-dialog :deep(.el-dialog__body) {
    padding: 15px;
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .library-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 0.75rem;
    padding: 0.25rem;
  }
  
  .library-item img {
    height: 150px;
  }
  
  .library-item-info {
    padding: 0.375rem;
    font-size: 0.8rem;
  }
  
  .empty-library {
    padding: 1.5rem;
  }
  
  .empty-library p {
    font-size: 0.875rem;
  }
}

/* 超小屏幕 */
@media (max-width: 375px) {
  .library-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 0.5rem;
  }
  
  .library-item img {
    height: 120px;
  }
  
  .library-dialog :deep(.el-dialog__header) {
    padding: 15px;
  }
  
  .library-dialog :deep(.el-dialog__footer) {
    padding: 10px 15px;
  }
  
  .library-dialog :deep(.el-button) {
    padding: 8px 12px;
    font-size: 0.875rem;
  }
}

/* 移动端菜单显示/隐藏 */
@media (max-width: 768px) {
  .desktop-menu {
    display: none !important;
  }
  
  .mobile-menu-btn {
    display: inline-flex !important;
  }
}

@media (min-width: 769px) {
  .desktop-menu {
    display: flex !important;
  }
  
  .mobile-menu-btn {
    display: none !important;
  }
}

/* 移动端抽屉菜单样式 */
.mobile-drawer :deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 1.5rem;
  background: linear-gradient(135deg, #ec4899 0%, #d946ef 50%, #8b5cf6 100%);
  border-bottom: none;
}

.drawer-header {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.drawer-logo {
  width: 40px;
  height: 40px;
}

.drawer-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  color: white;
  background: none;
  -webkit-background-clip: unset;
  -webkit-text-fill-color: white;
}

.mobile-drawer :deep(.el-drawer__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
}

.drawer-menu {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 1rem 0;
}

.menu-section {
  padding: 0 1rem;
  margin-bottom: 1rem;
}

.menu-section-title {
  font-size: 0.75rem;
  font-weight: 600;
  color: #9ca3af;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  padding: 0.5rem 0.75rem;
  margin-bottom: 0.25rem;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 0.75rem;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 0.25rem;
}

.menu-item:hover {
  background: linear-gradient(135deg, rgba(236, 72, 153, 0.1) 0%, rgba(217, 70, 239, 0.1) 100%);
  transform: translateX(4px);
}

.menu-item:active {
  transform: translateX(4px) scale(0.98);
}

.menu-icon {
  font-size: 1.25rem;
  color: #d946ef;
  min-width: 24px;
}

.menu-text {
  font-size: 1rem;
  font-weight: 500;
  color: #1f2937;
}

.menu-item-danger .menu-icon {
  color: #ef4444;
}

.menu-item-danger .menu-text {
  color: #ef4444;
}

.menu-item-danger:hover {
  background: rgba(239, 68, 68, 0.1);
}

.menu-divider {
  height: 1px;
  background: linear-gradient(90deg, transparent, #e5e7eb, transparent);
  margin: 1rem 0;
}

.menu-footer {
  margin-top: auto;
  padding: 1.5rem;
  background: linear-gradient(135deg, rgba(236, 72, 153, 0.05) 0%, rgba(217, 70, 239, 0.05) 100%);
  border-top: 1px solid rgba(217, 70, 239, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ec4899 0%, #d946ef 50%, #8b5cf6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.5rem;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 1rem;
  margin-bottom: 0.125rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-email {
  font-size: 0.875rem;
  color: #6b7280;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 抽屉打开动画 */
.mobile-drawer :deep(.el-drawer) {
  box-shadow: -4px 0 20px rgba(0, 0, 0, 0.1);
}
</style>
